<template>
	<view class="install-container" style="margin-bottom: 30rpx;">
		<view @click="handleDelete" class="delete-icon">X</view>
		<!-- 用户信息 -->
		<!-- 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，
		这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则 -->
		<uni-forms :value="params" ref="form" validateTrigger="bind" class="word5">
			<uni-forms-item required label="耗材分类：" name="类型名称">
				<!-- <input maxlength="50" placeholder="请输入起始楼层号" v-model="params['起始楼层号']" @input="binddata('起始楼层号',$event.detail.value)"> -->
				<song-data-picker :localdata="classList" popup-title="请选择耗材分类" :openSearch="true" @change="onchange" @nodeclick="onnodeclick"></song-data-picker>
			</uni-forms-item>
			<uni-forms-item v-if="goodsList.length" required label="耗材名称：" name="物料名称">
				<!-- <input type="number" maxlength="18" v-model="params['楼层数量']" placeholder="请输入申请单位" @input="binddata('楼层数量',$event.detail.value)" > -->
				<song-data-picker ref="songPicker" :localdata="goodsList" popup-title="请选择耗材" :openSearch="true" @change="onchange1" @nodeclick="onnodeclick"></song-data-picker>
			</uni-forms-item>
			<uni-forms-item v-show="materialInfo['规格型号']" required label="规格型号：" name="规格型号">
				<input disabled type="number" maxlength="18" v-model="materialInfo['规格型号']" placeholder="无" @input="binddata('楼层数量',$event.detail.value)" >
			</uni-forms-item>
			<uni-forms-item v-show="materialInfo['计量单位']" required label="计量单位：">
				<input disabled type="text" maxlength="18" v-model="materialInfo['计量单位']" placeholder="无" @input="binddata('楼层数量',$event.detail.value)" >
			</uni-forms-item>
			<uni-forms-item v-show="materialInfo['物料名称']" required label="总库存：" name="计量单位">
				<input disabled type="text" maxlength="18" v-model="materialInfo['物料数量']" placeholder="无" >
			</uni-forms-item>
			<uni-forms-item v-show="materialCount" required label="数量：" name="数量">
				<van-stepper @blur="handleBlur" @change="handleChange" input-width="120rpx" button-size="64rpx" :value="params['数量']" min="1" :max="materialInfo['物料数量']" />
			</uni-forms-item>
			<!-- <uni-forms-item required label="所属楼栋：" name="楼栋id">
				<view :class="label == '请选择所属楼栋' ? 'color':''" class="tap" @click="handleTap('picker')">{{label}}</view>
				<lb-picker ref="picker" @click="handleTap('picker')" v-model="params['楼栋id']"
				 mode="selector" :list="buildList" :dataset="{ name: 'label' }" @confirm="handleConfirm" @cancel="handleCancel">
				</lb-picker>
			</uni-forms-item> -->
			<!-- <button class="material-form-btn" @click="submitForm">提交</button> -->
			
		</uni-forms>
		<view class="line"></view>
	</view>
</template>

<script>
	import LbPicker from '@/components/lb-picker/index.vue'
	import dayjs from 'dayjs'
	export default {
		components: {
			LbPicker
		},
		props: {
			params: {
				type: Object,
				default: () => {}
			},
			classList: {
				type: Array,
				default: () => []
			},
			storeId: {
				type: Number
			}
		},
		data() {
			return {
				count: 1,
				materialCount: 0,
				materialInfo: {
					总库存: 1
				},
				formValue:{},
				goodsList: [],
				label: '请选择所属楼栋',
				// params: {
				// 	耗材分类: null,
				// 	耗材名称: null,
				// 	物料id: null,
				// 	数量	: 1,
				// 	计量单位: null,
				// 	规格型号: null,
				// },
				params2: {
					物料类别: null,
					所属机构: this.$config.groupId,
					所属仓库: null,
					pagination: {
						current: 1,
						pageSize: 1000
					},
					sorter: {
						field: "id",
						order: 0
					}
				},
				params3: {
					仓库id: null,
					物料id: null,
					pagination: {
						current: 1,
						pageSize: 100
					},
					sorter: {
						field: "id",
						order: 0
					}
				},
				//表单验证规则
				rules: {
					类型名称: {
						rules: [{
							required: true,
							errorMessage: '请选择耗材分类',
						}]
					},
					物料名称: {
						rules: [{
							required: true,
							errorMessage: '请选择耗材',
						}]
					}
				}
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad(options) {
			this.params2.所属仓库 = +options.id
		},
		methods: {
			
			handleDelete() {
				
				this.$emit('delete', this.params.id)
			},
			binddata(name,value){
			   // 通过 input 事件设置表单指定 name 的值
			   this.$refs.form.setValue(name, value)
			},
			handleChange(event) {
				this.count = event.detail - this.params.数量
				if(Math.abs(this.count) >= this.materialCount) {
					return
					// this.count = this.materialCount - this.params.数量
				}
				
				this.params.数量 = event.detail
				console.log('触发', this.count)
				this.getFormData()
			},
			handleBlur() {
				this.getFormData()
			},
			onchange(e) {
			  if(uni.getStorageSync('applyList')) {
				  let applyList = uni.getStorageSync('applyList')
				  const index = applyList.findIndex(item => item.id === this.params.id)
				  console.log('index', index)
				  if(index > -1) {
					  applyList.splice(index, 1)
					  uni.setStorageSync('applyList', applyList)
				  }
				  
				  
			  }
			  this.materialInfo = {
					总库存: 1
			  },
			  this.goodsList = []
			  // const value = e.detail.value
			  // this.params.耗材分类 = value[0].类型名称
			  this.materialInfo.类型名称 = e.detail.value[0].类型名称
			  this.params2.物料类别 = e.detail.value[0].类型id
			  this.binddata('类型名称', e.detail.value[0].类型名称)
			  // this.getFormData()
			  this.getGoodsList()
			},
			onchange1(e) {
			  console.log('e', e)
			  const value = e.detail.value[0]
			  let id = e.detail.value[0].物料ID
			  let applyList= uni.getStorageSync('applyList') || []
			  const item = applyList.find(item => item.物料id === id)
			  if(item) {
				  uni.showToast({
					  title:'列表中已有该耗材',
					  icon: 'none'
				  })
				  this.$refs.songPicker.inputSelected = []
				   console.log('ref', this.$refs.songPicker)
				  return
			  }
			 
			  this.materialInfo.物料数量 = ''
			  // this.formValue.物料id = value.物料ID
			  this.materialInfo = {...this.materialInfo, ...value}
			  this.materialInfo.物料id = value.物料ID
			  this.binddata('物料名称', value.物料名称)
			 
			  this.params3.物料id = value.物料ID
			  this.getStoreStock()
			  
			},
			getStoreStock() {
				this.params3.仓库id = this.storeId
				this.$http.post('/property/stuffStoreCount/list', this.params3).then(res => {
					if(res.code === 10000) {
						console.log('库存', res)
						res.data.list = res.data.list || []
						this.materialCount = res.data.list[0]?.物料数量
						this.materialInfo.物料数量 = res.data.list[0]?.物料数量
						this.getFormData()
					}
				})
			},
			async getClassList() {
				uni.showLoading({
					mask: true
				})
				const res = await this.$http.post('/property/typeSetting/list', this.params1)
				if(res.code === 10000) {
					console.log(res)
					res.data.list.forEach(item => {
						item.text = item.类型名称
						item.value = item.类型id
					})
					this.classList = res.data.list
				}
			},
			async getGoodsList() {
				this.params2.所属仓库 = this.storeId
				console.log('id', this.storeId)
				const res = await this.$http.post('/property/consumable/list', this.params2)
				if(res.code === 10000) {
					console.log(res)
					res.data.list = res.data.list || []
					res.data.list.forEach(item => {
						item.text = item.物料名称
						item.value = item.物料ID
					})
					this.goodsList = res.data.list
					if(!this.goodsList.length) {
						uni.showToast({
							title: '当前分类无耗材',
							icon: 'none'
						})
					}
				}
			},
			getFormData(){
				
				let params = Object.assign({}, this.params, this.materialInfo)
				console.log('params', params)
				console.log('数量', this.materialCount)
				let applyItem =  [{ id: params.id, 物料id: params.物料id, 数量: params.数量 }]
				if(!this.materialCount) {
					applyItem[0].数量 = 0
				}
				if(!uni.getStorageSync('applyList')) {
					uni.setStorageSync('applyList', applyItem)
				}else {
					
					let applyList = uni.getStorageSync('applyList')
					const index = applyList.findIndex(item => item.id === params.id)
					console.log('index', index)
					// const item = applyList.find(item => item.物料id === params.物料id)
					if(index > -1) {
						applyList[index] = applyItem[0]
						console.log('触发了', index, applyList)
						// item = applyItem
						// console.log('item', item)
						// uni.setStorageSync('applyList', applyList)
					}else {
						
						applyList = applyList.concat(applyItem)
						// const item = applyList.find(item => item.物料id === params.物料id)
						// if(item) {
						// 	console.log('1', item.数量)
						// 	console.log('2', params.数量)
						// 	let count = (item.数量 + this.count) > this.materialCount ? this.materialCount : (item.数量 + this.count)
						// 	item.数量 = count
						// }else {
						// 	applyList = applyList.concat(applyItem)
						// }
						
						// uni.setStorageSync('applyList', applyList)
					}
					uni.setStorageSync('applyList', applyList)
				}
				console.log('applyItem', applyItem)
				// console.log('params', Object.assign({},this.params,this.materialInfo))
				return
				this.$emit('update:params',Object.assign({},this.params,this.materialInfo))
				this.$emit('onShow')
			},
			//校验表单，通过返回true，否则返回false
			validate(){
				this.$refs.form.submit().then(res => {
					// console.log('成功了')
				}).catch(err => {
					console.log('表单错误信息：', err);
					uni.showToast({
						icon: 'none',
						title: "表单字段填写错误，请检查"
					})
					return false
				})
				return true
			}
		}
	}
</script>

<style lang="scss" scoped>
	.delete-icon {
		display: flex;
		justify-content: flex-end;
		padding-right: 30rpx;
		font-size: 42rpx;
		color: #999;
	}
	.line {
		margin-top: 100rpx;
		// margin-bottom: 40rpx;
		width: 710rpx;
		margin-left: 20rpx;
		height: 2rpx;
		background-color: #ccc;
	}
	.install-container {
		// height: 100vh;
		// background-color: #F8F8F8;
	}
	.color {
		color: #808080;
	}
	.tap {
		display: flex;
		align-items: center;
	}
</style>

